package se.webbzon.boltzmann.editor.component;

import java.awt.BorderLayout;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

public class JCombinedTextField extends JPanel {
	
	// Auto generated serial version UID
	private static final long serialVersionUID = -8402803996358766381L;
	
	// The maximal length of the text in this combined text field
	private final int maxLength;

	// The text field of this combined text field
	private final JTextField textField;
	
	// The character counter of this combined text field
	private final JLabel label;
	
	/*============================================================
	Constructors
	============================================================*/
	
	public JCombinedTextField(String str) {
		this(str,-1);
	}
	
	public JCombinedTextField(String str, int maxLength) {
		this.maxLength = maxLength;
		setLayout(new BorderLayout());
		
		textField = new JTextField(str);
		textField.addCaretListener(new CaretListenerImpl());
		add(textField,BorderLayout.CENTER);
		if (maxLength > 0)
			label = new JLabel("0/" + str.length() + "/" + maxLength);
		else
			label = new JLabel("0/" + str.length());
		add(label,BorderLayout.EAST);
	}
	
	/*============================================================
	Public Methods
	============================================================*/
	
	/** Returns the text of this combined text field. **/
	public String getText() {
		return textField.getText();
	}
	
	/** Sets the text of this combined text field. **/
	public void setText(String str) {
		textField.setText(str);
	}
	
	/*============================================================
	Private Classes
	============================================================*/
	
	private final class CaretListenerImpl implements CaretListener {

		@Override
		public void caretUpdate(CaretEvent arg0) {
			System.out.println();
			final int length = textField.getText().length();
			final int pos = textField.getCaretPosition();
			if (maxLength > 0)
				label.setText(pos + "/" + length + "/" + maxLength);
			else
				label.setText(pos + "/" + length);
		}
		
	}

}
